import json
from django.shortcuts import render
from django.views.generic import View
from django.http import JsonResponse, HttpResponse
from .models import BookInfo
from rest_framework.viewsets import ModelViewSet
from .serializers import BookInfoSerializers

# Create your views here.

# 获取所有书籍
# get /books

# 获取一本书
# get /books/id

# 添加，json数据格式
# post

# 更新一本书
# put /books/id

# 删除一本书
# delete /books/id


class BooksView(View):
    def get(self, request):
        books = BookInfo.objects.all()
        books_list = []
        for book in books:
            books_list.append({
                'id': book.id,
                'btitle': book.title,
                'bcomment': book.bcomment,
                'bread': book.bread,
                'bpub_date': book.bpub_date,
                'image': book.image.url if book.image else ''
            })

        return JsonResponse(books_list, safe=False)

    def post(self, request):
        body_data = request.body
        str_data = body_data.decode()
        data = json.loads(str_data)

        book = BookInfo.objects.create(
            btitle=data['btitle'],
            bpub_date=data['bpub_date']
        )

        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        })


class BookView(View):
    def get(self, requesr, id):
        try:
            book = BookInfo.objects.get(id=id)
        except Exception as e:
            raise e

        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        })

    def put(self, request, id):
        try:
            book = BookInfo.objects.get(id=id)
        except Exception as e:
            raise e

        body_data = request.body
        str_body = body_data.decode()
        data = json.loads(str_body)

        book.btitle = data['btitle']
        book.bpub_date = data['bpub_date']
        book.save()

        return JsonResponse({
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        })

    def delete(self, request, id):
        try:
            book = BookInfo.objects.get(id=id)
        except Exception as e:
            raise e

        book.delete()

        return HttpResponse('OK')


class BookInfoViewset(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookInfoSerializers